# 创建元组
tup1 = (1, 2, 3)          # 标准创建方式
tup2 = 4, 5, 6            # 省略括号写法
single_tup = (7,)          # 单元素元组必须有逗号
empty_tup = ()             # 空元组

print(type(tup1))          # <class 'tuple'>
print(tup2)                # (4, 5, 6)

# 尝试修改元组（会报错）
try:
    tup1[0] = 10           # TypeError: 'tuple' object does not support item assignment
except TypeError as e:
    print(f"错误：{e}")

# 元组的合法"修改"方式（实际是创建新元组）
new_tup = tup1 + (4,)      # 连接元组
print(new_tup)             # (1, 2, 3, 4)









import sys
lst = [1, 2, 3]
tup = (1, 2, 3)

print(sys.getsizeof(lst))  # 88 (列表占用更多内存)
print(sys.getsizeof(tup))  # 64 (元组更紧凑)

# 元组在字典中作为键的演示
valid_dict = {(1,2): "坐标"}  # 元组可哈希，可作为键
invalid_dict = {[1,2]: "列表"} # 报错：列表不可哈希














# 创建字典
student = {"name": "张三", "age": 20, "courses": ["Math", "CS"]}

# 访问元素
print(student["name"])      # "张三"（键不存在会报KeyError）
print(student.get("grade", "N/A"))  # "N/A"（安全访问）

# 添加/修改元素
student["age"] = 21         # 修改已有键
student["grade"] = "A"      # 添加新键
print(student)              # {'name': '张三', 'age': 21, 'courses': ['Math', 'CS'], 'grade': 'A'}

# 删除元素
del student["courses"]      # 删除键
popped = student.pop("age") # 删除并返回值
print(f"删除的年龄: {popped}, 剩余: {student}")










dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}

# 方法1：update()（原地修改）
dict1.update(dict2)
print(dict1)  # {'a': 1, 'b': 3, 'c': 4}

# 方法2：合并运算符（Python 3.9+）
new_dict = dict1 | dict2    # 新建合并字典
print(new_dict)











for key in student:
    print(key)

# 等价于
for key in student.keys():
    print(key)

for value in student.values():
        print(value)

for key, value in student.items():
            print(f"{key}: {value}")


for key in sorted(student.keys()):
    print(f"{key} -> {student[key]}")


squared = {x: x**2 for x in range(5)}
print(squared)  # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}


def word_frequency(text):
    freq = {}
    for word in text.lower().split():
        freq[word] = freq.get(word, 0) + 1
    return freq

text = "Python is easy Python is powerful"
result = word_frequency(text)

# 按频率降序打印
for word, count in sorted(result.items(), key=lambda x: -x[1]):
    print(f"{word}: {count}次")











# 通讯录管理系统
class ContactManager:
    def __init__(self):
        self.contacts = {}  # 使用字典存储姓名-电话

    def add_contact(self, name, phone):
        """添加联系人"""
        if name in self.contacts:
            print(f"【警告】{name} 已存在，当前电话：{self.contacts[name]}")
            if input("是否更新？(y/n): ").lower() == 'y':
                self.contacts[name] = phone
                print("更新成功！")
        else:
            self.contacts[name] = phone
            print(f"已添加：{name} - {phone}")

    def delete_contact(self, name):
        """删除联系人"""
        if name in self.contacts:
            print(f"删除：{name} - {self.contacts.pop(name)}")
        else:
            print(f"【错误】未找到联系人：{name}")

    def search_contact(self, name):
        """查找联系人"""
        phone = self.contacts.get(name, None)
        if phone:
            print(f"找到联系人：{name} - {phone}")
        else:
            print(f"未找到：{name}")

    def show_all(self):
        """显示所有联系人"""
        print("\n=== 通讯录 ===")
        for name, phone in self.contacts.items():
            print(f"{name:<10}: {phone}")
        print(f"共 {len(self.contacts)} 个联系人")


# 使用示例
manager = ContactManager()
manager.add_contact("张三", "13800138000")
manager.add_contact("李四", "13912345678")
manager.add_contact("张三", "15900000000")  # 触发更新

manager.search_contact("李四")  # 找到联系人：李四 - 13912345678
manager.delete_contact("王五")  # 【错误】未找到联系人：王五
manager.show_all()
"""
=== 通讯录 ===
张三      : 15900000000
李四      : 13912345678
共 2 个联系人
"""







import re
from collections import Counter

def word_frequency(text, ignore_case=True):
    """统计文本中单词出现频率"""
    # 清洗文本：去除非字母字符并分割单词
    if ignore_case:
        text = text.lower()
    words = re.findall(r'\b\w+\b', text)  # 匹配单词边界
    return Counter(words)  # 使用Counter统计

# 示例文本
sample_text = """
Python is powerful, and Python is fast. 
It's also easy to learn! Python 3.10 released in 2021.
"""

# 统计并展示结果
freq = word_frequency(sample_text)
print("单词频率统计:")
for word, count in freq.most_common(5):  # 显示前5高频词
    print(f"{word}: {count}次")

# 扩展：排除停用词
stop_words = {"is", "and", "it", "in", "to"}
filtered_freq = {k:v for k,v in freq.items() if k not in stop_words}
print("\n过滤后的高频词:", filtered_freq)







import json

def save_contacts(contacts, filename="contacts.json"):
    with open(filename, 'w') as f:
        json.dump(contacts, f)

def load_contacts(filename="contacts.json"):
    try:
        with open(filename) as f:
            return json.load(f)
    except FileNotFoundError:
        return {}

# 在ContactManager类中添加：
def save_to_file(self, filename="contacts.json"):
    save_contacts(self.contacts, filename)

@classmethod
def load_from_file(cls, filename="contacts.json"):
    manager = cls()
    manager.contacts = load_contacts(filename)
    return manager







# 安装：pip install wordcloud matplotlib
from wordcloud import WordCloud
import matplotlib.pyplot as plt

def generate_wordcloud(freq_dict):
    wc = WordCloud(width=800, height=400, background_color='white')
    wc.generate_from_frequencies(freq_dict)
    plt.imshow(wc, interpolation='bilinear')
    plt.axis("off")
    plt.show()

# 使用示例
generate_wordcloud(freq)


def show_by_group(self):
    groups = {}
    for name in self.contacts:
        initial = name[0].upper()
        groups.setdefault(initial, []).append(name)

    for initial in sorted(groups):
        print(f"\n[{initial}]")
        for name in sorted(groups[initial]):
            print(f"{name}: {self.contacts[name]}")